<template>
  <a-form ref="formRef" :model="formModel" class="link-container">
    <!-- 链接类型：{{ linktype }} -->
    <!-- 修改的时候标题不可以修改 -->
    <a-form-item :label-col-flex="'0px'">
      <a-input v-model="formModel.linkText" placeholder="请输入链接文本" />
    </a-form-item>
    <!-- 如果是普通链接，则显示链接地址 文章链接下隐藏 -->
    <a-form-item v-if="linktype === 'customLink' || linktype === 'customLink-edit'" :label-col-flex="'0px'">
      <a-input v-model="formModel.linkAddress" placeholder="请输入链接文本" />
    </a-form-item>
    <!-- 如果是文章链接，则显示文章id -->
    <a-form-item
      v-if="linktype === 'article' || linktype === 'article-edit' || linktype === 'link-card'"
      :label-col-flex="'0px'"
    >
      <a-input v-model="formModel.articleId" placeholder="请输入链接文章ID" />
    </a-form-item>
    <p class="tip-text">{{ getFormModelTipText() }}</p>
  </a-form>
  <div class="arco-modal-footer arco-modal-footer-custom">
    <a-button @click="handleConfirm('no')">取消</a-button>
    <a-button type="primary" @click="handleConfirm('ok')">确定</a-button>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, computed } from 'vue';
  import { checkArticleId } from '../module/customLink/menu/checkArticleId';
  import { validateLink } from '../module/customLink/menu/validateLink';
  interface LinkData {
    type?: string;
    linkAddress?: string;
    linkText?: string;
    articleId?: string;
    link?: string;
    target?: string;
  }
  const props = defineProps<{
    linktype: string;
    linkData: LinkData;
  }>();

  const emit = defineEmits(['insertCustomLinkConfirm', 'setLoadingFlag', 'updateCustomLinkConfirm', 'cancel']);
  const formModel = ref({
    linkText: '',
    linkAddress: '',
    articleId: '',
  });

  // 是否是修改状态
  const isEditing = computed(() => props.linkData?.type !== undefined);

  const getFormModelTipText = () => {
    // props.linktype === 'customLink'
    if (props.linktype === 'customLink' || props.linktype === 'customLink-edit') {
      return '请插入http、https、ftp、www开头的链接地址';
    } else if (props.linktype === 'article' || props.linktype === 'article-edit' || props.linktype === 'link-card') {
      return '请在白桃星球APP-文章详情-右上角的更多- 复制文章ID';
    }
  };

  watch(
    () => props.linkData,
    () => {
      if (props.linkData) {
        // 如果名称前后有书名号，则需要去掉书名号再赋值
        const articleTitle = props.linkData.linkText?.replace(/^《|》$/g, '');
        formModel.value = {
          ...formModel.value,
          ...(props.linkData.type ? { linkText: articleTitle } : {}),
          ...(props.linktype === 'customLink-edit' ? { linkAddress: props.linkData.linkAddress } : {}),
          ...(props.linktype === 'article-edit' || props.linktype === 'link-card'
            ? { articleId: props.linkData.articleId }
            : {}),
        };
      }
    },
    { immediate: true, deep: true },
  );

  // 校验合法
  const handleConfirm = (type: string) => {
    const action = isEditing.value ? 'updateCustomLinkConfirm' : 'insertCustomLinkConfirm';
    if (type == 'no') {
      emit('cancel');
    } else {
      emit('setLoadingFlag', true);
      const { linkText, linkAddress, articleId } = formModel.value;
      if (props.linktype === 'customLink' || props.linktype === 'customLink-edit') {
        if (validateLink({ text: linkText, link: linkAddress })) {
          emit(action, {
            text: linkText,
            link: linkAddress,
            target: '_blank',
            linkType: props.linktype,
            articleId: articleId,
          });
        }
      } else if (props.linktype === 'article' || props.linktype === 'article-edit' || props.linktype === 'link-card') {
        const target = `article_${articleId}`;
        // 名称需要加书名号 如果输入的名称有书名号，则不加，需要做兼容性处理
        try {
          checkArticleId({ title: linkText, articleId }).then((res) => {
            if (res) {
              let linkArticleText = res.text;
              // 检查是否已经被《》包裹，如果没有则保持原样
              if (linkArticleText.startsWith('《') && linkArticleText.endsWith('》')) {
                linkArticleText = linkArticleText;
              } else {
                linkArticleText = `《${linkArticleText}》`;
              }
              emit(action, {
                text: linkArticleText,
                link: res.link,
                target,
                linkType: props.linktype,
                articleId: articleId,
              });
            }
          });
        } catch (err) {
          console.log('error', err);
        }
      }

      emit('setLoadingFlag', false);
    }
  };
</script>
<style lang="less">
  .link-container {
    .arco-input-wrapper {
      border-radius: 8px 8px 8px 8px;
      border: 1px solid #e5e6eb;
      padding: 4px;
    }
    .arco-input-wrapper .arco-input.arco-input-size-medium {
      padding: 4px 13px;
      font-size: 18px;
    }

    .arco-form-item-label-col {
      padding-right: 0;
    }
    .arco-input-wrapper:hover {
      border: 1px solid #bfc3cd;
      border-radius: 8px 8px 8px 8px;
    }
    .tip-text {
      font-size: 14px;
      color: #999ca1;
      text-align: center;
    }
    .btn-group {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
